﻿

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Collections;
using System.IO;



namespace Fingu.ATF.Testing
{
    public partial class PowerEfficient : Form
    {

        public TestingEnter testingEnter;
        public string[] datas;
        public bool[] testResult;
        public bool[] testStep;
        public double testLimit = 0.205;
        string msg;

        /// //////////////////////////////////////////////////////////////////////////
        ///date:2012-12-07
        ///author:xiejun
        ///content:
        ///defind some of variable use for save testStep,productCommand,testIndex,
        ///fixtureCommand,testLimit.        
        /// ///////////////////////////////////////////////////////////////////////
        string[] _testStep;
        string[] _productCommand;
        string[] _testIndex;
        string[] _fixtureCommand;
        string[] _testLimit;

        public PowerEfficient()
        {
            InitializeComponent();            
        }
        private void btnComSwitch_Click(object sender, EventArgs e)
        {
            ChooseInitType(testingEnter.GetTestType());

            if (cobComPortName.Text == "Choose")
            {
                MessageBox.Show("please choose a com port!", "error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (testingEnter._tmr045.CheckComWhetherInitialization() == false)
            {
                testingEnter._tmr045.InitCom(cobComPortName.Text, 4800, 8, out msg);
            }

            if (btnComSwitch.Text == "ON")
            {
                testingEnter._tmr045.openCom();
                btnComSwitch.Text = "OFF";
                btnComSwitch.BackColor = Color.LightGreen;
                cobComPortName.BackColor = Color.LightGreen;
            }
            else
            {
                testingEnter._tmr045.closeCom();
                btnComSwitch.Text = "ON";
                btnComSwitch.BackColor = Color.Red;
                cobComPortName.BackColor = Color.Red;
            }

        }
        private void txtSGFrequency_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                //testingEnter.iSG1.SetRFFrequency(long.Parse(txtSGFrequency.Text) * 10 ^ 6);
                testingEnter.iSG1.SetRFFrequency(2595000000);
            }

            if (Keys.Enter.CompareTo((System.Windows.Forms.Keys)e.KeyChar) == 0)
            {
                //testingEnter.iSG1.SetRFFrequency(long.Parse(txtSGFrequency.Text) * 10 ^ 6);
                testingEnter.iSG1.SetRFFrequency(2595000000);
            }
        }
        private void lstSGOffSet_SelectedIndexChanged(object sender, EventArgs e)
        {
            testingEnter.iSG1.SetRFAmplitude(0);
        }
        private void txtSpecFrequency_KeyPress(object sender, KeyPressEventArgs e)
        {
            //long val = Convert.ToInt16(txtSpecFrequency.Text) * 10 ^ 6;
            if (e.KeyChar == Convert.ToChar(Keys.Enter))
            {
                //testingEnter.iSA.SetCenterFrequency(long.Parse(txtSpecFrequency.Text) * 10 ^ 6);
                testingEnter.iSA.SetCenterFrequency(2595000000);
            }

            if (Keys.Enter.CompareTo((System.Windows.Forms.Keys)e.KeyChar) == 0)
            {
                //testingEnter.iSA.SetCenterFrequency(long.Parse(txtSpecFrequency.Text) * 10 ^ 6);
                testingEnter.iSA.SetCenterFrequency(2595000000);
            }
        }
        private void lstSpecOffSet_SelectedIndexChanged(object sender, EventArgs e)
        {
            testingEnter.iSA.SetRefLvlOffset(47.10);
            testingEnter.iSA.SetFrequencySpan(10000);
        }
        private void btnPAChannelAll_Click(object sender, EventArgs e)
        {
            testingEnter._tmr045.SetRichTextBox(richTextBox1);

            switch (btnPAChannelAll.Text)
            {
                case "ON":
                    testingEnter._tmr045.sendCommand("OPEN_ALL_PA");
                    testingEnter._tmr045.receiveCommand();
                    btnPAChannelAll.Text = "OFF";
                    btnPAChannelAll.BackColor = Color.LightGreen;
                    txtPAChannelAll.BackColor = Color.LightGreen;

                    break;

                case "OFF":
                    testingEnter._tmr045.sendCommand("CLOSE_ALL_PA");
                    testingEnter._tmr045.receiveCommand();
                    btnPAChannelAll.Text = "ON";
                    btnPAChannelAll.BackColor = Color.Red;
                    txtPAChannelAll.BackColor = Color.Red;

                    break;
            }

        }
        private void btnPAChannelOne_Click(object sender, EventArgs e)
        {
            //SinglePortTest();
            ChooseTestType(testingEnter.GetTestType());
        }
        private void btSave_Click(object sender, EventArgs e)
        {
            if (CheckTestStep() == true)
            {
                InitTestResult();
                InitalizationTestStepState();
                InitCobPACHannelOne();
                btnPAChannelOne.Focus();
                testingEnter.SetCobTestRoad(cobPAChannelOne);
                testingEnter.SetTestDatas(datas);
                testingEnter.SetCheckOutState(cobCheckState.Text);
                testingEnter.SetTestResult(GetTestResult(testResult));
                testingEnter.Save();
            }
            else if (CheckTestStep() == false)
            {
                btnPAChannelOne.Focus();
                MessageBox.Show("测试步骤不完整！","提示", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
            }


        }
        private void btPrevious_Click(object sender, EventArgs e)
        {
            testingEnter.Previous();
        }
        private void P1VoltValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            testingEnter.iPM1.SetVOLT(28.5);
            testingEnter.iPM1.SetCurrent(10);
        }
        private void P2VoltValue_KeyPress(object sender, KeyPressEventArgs e)
        {
            testingEnter.iPM2.SetVOLT(5.7);
            testingEnter.iPM2.SetCurrent(10);
        }
        private void btnCalibrate_Click(object sender, EventArgs e)
        {
            ChooseCalibarteType(testingEnter.GetTestType());
        }
        private void btnCallCalibrate_Click(object sender, EventArgs e)
        {
            if (ReadOffsetCableAddAttenuator() == true)
            {
                MessageBox.Show("校准值调用完毕！");
            }
        }
        private void cobPAChannelOne_SelectedIndexChanged(object sender, EventArgs e)
        {
            //txtP1CurrentValue_PA_On.Text = "";
            //txtP1CurrentValue_PA_Off.Text = "";
            //txtP2CurrentValue_PA_On.Text = "";
            //txtP2CurrentValue_PA_Off.Text = "";
            //txtAmplifierEffectiveValue.Text = "";
        }
        private void btnExport_Click(object sender, EventArgs e)
        {
            frmExport _frmExport = new frmExport();
            _frmExport.Show();
        }

        private bool bFirstTime = false;
        private bool bSecondTime = false;
        private bool ReadCurrentValue_FirstTime()
        {
            try
            {
                //-------------------------1-------------------------
                //打开电源
                testingEnter.iPM2.OutSwitch("ON");
                testingEnter.iPM1.OutSwitch("ON");
                //发PA指令
                testingEnter._tmr045.sendCommand(_productCommand[cobPAChannelOne.SelectedIndex]);
                Thread.Sleep(1000);
                testingEnter._tmr045.receiveCommand();
                //发PA指令
                testingEnter._tmr045.sendCommand(_productCommand[cobPAChannelOne.SelectedIndex]);
                testingEnter._tmr045.receiveCommand();

                //调功率，让频谱仪的功率值达到40dBm
                testingEnter.iSG1.SetRFAmplitude(-30);
                testingEnter.iSG1.SetRFOutputState(true);

                DebugPower();

                if (GetDebugPowerState() == false)
                {
                    bFirstTime = false;

                    return false;
                }
                else
                {
                    bFirstTime = true;

                    return true;
                }
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
                bFirstTime = false;
                return false;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
                bFirstTime = false;
                return false;
            }
        }
        private bool ReadCurrentValue_SecondTime()
        {
            try
            {
                double current5Point5_OFF_Value = 0;
                double current28_OFF_Value = 0;
                //string outSwtich = "";
                //-------------------------2-------------------------
                Thread.Sleep(2000);
                ////关闭电源后
                //testingEnter.iPM2.OutSwitch("OFF");
                //testingEnter.iPM1.OutSwitch("OFF");
                //发PA指令
                testingEnter._tmr045.sendCommand("CLOSE_ALL_PA");
                testingEnter._tmr045.receiveCommand();
                //读28v的电流值
                testingEnter.iPM1.GetCurrent(ref current28_OFF_Value);
                testingEnter._tmr045.SetCurrent28_SecondTime(current28_OFF_Value);
                txtP2CurrentValue_PA_Off.Text = current28_OFF_Value.ToString();
                //读5.5v的电源值
                testingEnter.iPM2.GetCurrent(ref current5Point5_OFF_Value);
                testingEnter._tmr045.SetCurrent5Point5_SecondTime(current5Point5_OFF_Value);
                txtP1CurrentValue_PA_Off.Text = current5Point5_OFF_Value.ToString();

                bSecondTime = true;

                return true;
            }
            catch (NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
                bSecondTime = false;
                return false;
            }
            catch (ArgumentException ex)
            {
                MessageBox.Show(ex.Message);
                bSecondTime = false;
                return false;
            }
        }
        private bool _debugPowerState = false;
        public void SetDebugPowerState(bool arg)
        {
            this._debugPowerState = arg;
        }
        public bool GetDebugPowerState() 
        {
            return this._debugPowerState;
        }
        private void DebugPower()
        {
            double power = 0;
            double resultPower = 0;
            double power2 = 0;
            double power3 = 0;
            double power4 = 0;
            double current5Point5_ON_Value = 0;
            double current28_ON_Value = 0;

            SetSGPowerWhetherRangeLimit(false);
            testingEnter.iSA.GetPower(ref power);
            power2 = Math.Abs(power);

            if (power >= 39.96 && power <= 40.08)
            {
                Thread.Sleep(2000);
                //读28v的电流值
                testingEnter.iPM1.GetCurrent(ref current28_ON_Value);
                testingEnter._tmr045.SetCurrent28_FirstTime(current28_ON_Value);
                txtP2CurrentValue_PA_On.Text = current28_ON_Value.ToString();
                //5.5v的电流值
                testingEnter.iPM2.GetCurrent(ref current5Point5_ON_Value);
                testingEnter._tmr045.SetCurrent5Point5_FirstTime(current5Point5_ON_Value);
                txtP1CurrentValue_PA_On.Text = current5Point5_ON_Value.ToString();
                testingEnter.iSG1.SetRFOutputState(false);
                SetDebugPowerState(true);
                return;
            }
            else if (39.96 - power >= 3)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power3 = resultPower + 1;
                testingEnter.iSG1.SetRFAmplitude(power3);
                Thread.Sleep(200);
            }
            else if (39.96 - power < 3 && 39.96 - power >= 1)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power3 = resultPower + 0.5;
                testingEnter.iSG1.SetRFAmplitude(power3);
                Thread.Sleep(200);
            }
            else if (39.96 - power < 1 && 39.96 - power >= 0.2)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power3 = resultPower + 0.1;
                testingEnter.iSG1.SetRFAmplitude(power3);
                Thread.Sleep(200);
            }
            else if (39.96 - power < 0.2 && 39.96 - power >= 0.12)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power3 = resultPower + 0.05;
                testingEnter.iSG1.SetRFAmplitude(power3);
                Thread.Sleep(200);
            }
            else if (39.96 - power < 0.12)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power3 = resultPower + 0.02;
                testingEnter.iSG1.SetRFAmplitude(power3);
                Thread.Sleep(200);
            }
            else if (power >= 40.3)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power4 = resultPower - 0.1;
                testingEnter.iSG1.SetRFAmplitude(power4);
                Thread.Sleep(200);
            }
            else if (power > 40.3 && power < 40.08)
            {
                testingEnter.iSG1.GetPower(ref resultPower);
                power4 = resultPower - 0.05;
                testingEnter.iSG1.SetRFAmplitude(power4);
                Thread.Sleep(200);
            }

            if (resultPower > -5)
            {
                SetSGPowerWhetherRangeLimit(true);
                testingEnter.iSG1.SetRFOutputState(false);
                MessageBox.Show("信号源功率过大，请检查！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                SetDebugPowerState(false);
                return;
            }

            DebugPower();

        }
        private bool _SGPowerWhetherRangeLimit = false;
        private void SetSGPowerWhetherRangeLimit(bool state)
        {
            this._SGPowerWhetherRangeLimit = state;
        }
        private bool GetSGPowerWhetherRangeLimit()
        {
            return this._SGPowerWhetherRangeLimit;
        }
        private void InitaliaztionTestBoardTestValue()
        {
            txtP1CurrentValue_PA_On.Text = "";
            txtP1CurrentValue_PA_Off.Text = "";
            txtP2CurrentValue_PA_On.Text = "";
            txtP2CurrentValue_PA_Off.Text = "";
            txtAmplifierEffectiveValue.Text = "";
        }
        private void InitaliaztionTestBoardTestValueCobValue()
        {
            txtP1CurrentValue_PA_On.Text = "";
            txtP1CurrentValue_PA_Off.Text = "";
            txtP2CurrentValue_PA_On.Text = "";
            txtP2CurrentValue_PA_Off.Text = "";
            txtAmplifierEffectiveValue.Text = "";
            cobPAChannelOne.SelectedIndex = 0;
            cobCheckState.SelectedIndex = 0;
            testingEnter.SetTestResult(GetTestResult(testResult));
            InitTestResult();
            InitalizationTestStepState();
            InitCobPACHannelOne();

        }
        private void InitTestResult()
        {
            for (int i = 0; i <= testResult.Length - 1; i++)
            {
                testResult[i] = false;
            }
        }
        private void InitCobPACHannelOne()
        {
            cobPAChannelOne.SelectedIndex = 0;
        }
        private void InitCheckOutState()
        {
            string[] checkOutState = new string[] { "一检", "二检", "终检", "客退" };
            foreach (string arg in checkOutState)
            {
                cobCheckState.Items.Add(arg);
            }
            cobCheckState.SelectedIndex = 0;
        }
        private int GetTestResult(bool[] arg)
        {
            int iCount = -1;

            int result = 0;

            foreach (bool b in arg)
            {               
                if (b == false)
                {
                    result = 1;
                    return result;
                }
                else if (b == true)
                {
                    iCount++;

                    if (iCount == arg.Length)
                    {
                        result = 0;
                    }
                    
                }
            }

            return result;
        }
        private void SinglePortTest()
        {
            SetTestStepState(cobPAChannelOne.SelectedIndex);

            InitaliaztionTestBoardTestValue();

            testingEnter._tmr045.SetRichTextBox(richTextBox1);

            if (ReadCurrentValue_FirstTime() == false)
            {
                AmplifierEffectiveValueIsUnQuality();
                return;
            }

            ReadCurrentValue_SecondTime();

            DisplayTestValue();
        }
        private void DisplayTestValue()
        {
            if (bFirstTime == true && bSecondTime == true)
            {
                if (testingEnter._tmr045.CalculatorPowerEfficient() >
                    Convert.ToDouble(testingEnter.GetTestLimitLeft()[cobPAChannelOne.SelectedIndex]) &&
                    testingEnter._tmr045.CalculatorPowerEfficient() <
                    Convert.ToDouble(testingEnter.GetTestLimitRight()[cobPAChannelOne.SelectedIndex]))
                {
                    AmplifierEffectiveValueIsQuality();
                }
                else
                {
                    AmplifierEffectiveValueIsUnQuality();
                    return;
                }

                datas[cobPAChannelOne.SelectedIndex] = txtAmplifierEffectiveValue.Text.Replace("\n", "");
                testingEnter._tmr045.SetRichTextBox(richTextBox2);
                testingEnter._tmr045.DisplayCommandInformationInRichBox
                    (cobPAChannelOne.Text.Replace("OPEN_", ""), txtAmplifierEffectiveValue.Text);
                bFirstTime = false;
                bSecondTime = false;

                CloseAllPAWhencobPACHannelOneWasThree();

                CheckTestingWetherEnd();

                ChangecobPAChannelOne();
            }
        }
        private void CloseAllPAWhencobPACHannelOneWasThree()
        {
            if (cobPAChannelOne.SelectedIndex == 3)
            {
                testingEnter._tmr045.sendCommand("CLOSE_ALL_PA");
                testingEnter._tmr045.receiveCommand();
                testingEnter.iSG1.SetRFOutputState(false);
                testingEnter.iPM1.OutSwitch("OFF");
                testingEnter.iPM2.OutSwitch("OFF");
                MessageBox.Show("PA关闭，信号源功率关闭，电源1,2输出关闭，可以更换产品的电缆。",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void AmplifierEffectiveValueIsUnQuality()
        {
            if (GetSGPowerWhetherRangeLimit() == true)
            {
                testResult[cobPAChannelOne.SelectedIndex] = false;
                txtAmplifierEffectiveValue.Text = String.Format("{0:P}", testingEnter._tmr045.CalculatorPowerEfficient());
                txtAmplifierEffectiveValue.BackColor = Color.Red;
                MessageBox.Show("测试结果不合格！" + String.Format("{0:P}", testingEnter._tmr045.CalculatorPowerEfficient()),
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void AmplifierEffectiveValueIsQuality()
        {
            if (GetSGPowerWhetherRangeLimit() == false)
            {
                testResult[cobPAChannelOne.SelectedIndex] = true;
                txtAmplifierEffectiveValue.Text =
                    String.Format("{0:P}", testingEnter._tmr045.CalculatorPowerEfficient());
                txtAmplifierEffectiveValue.BackColor = Color.LightGreen;
            }

        }
        private void ChangecobPAChannelOne()
        {
            if (GetSGPowerWhetherRangeLimit() == false)
            {
                if ((cobPAChannelOne.SelectedIndex) == cobPAChannelOne.Items.Count - 1)
                {
                    //
                    InitaliaztionTestBoardTestValueCobValue();
                }
                else
                {
                    cobPAChannelOne.SelectedIndex += 1;
                }
            }
        }
        private void CheckTestingWetherEnd()
        {
            InitalizationTestBoard();
        }
        private void CloseAllFixture()
        {
            testingEnter._tmr045.sendCommand("CLOSE_ALL_PA");
            testingEnter._tmr045.receiveCommand();
            testingEnter.iSG1.SetRFOutputState(false);
            testingEnter.iPM1.OutSwitch("OFF");
            testingEnter.iPM2.OutSwitch("OFF");
        }
        private void TestingIsGood() 
        {
            if (cobPAChannelOne.SelectedIndex == 7 && CheckTestResultState() == true)
            {
                CloseAllFixture();

                MessageBox.Show("测试完毕！当前产品：合格",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void TestingIsBad()
        {
            if (cobPAChannelOne.SelectedIndex == 7 && CheckTestResultState() == false)
            {
                CloseAllFixture();

                MessageBox.Show("测试完毕！当前产品：不合格",
                    "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void InitalizationTestBoard()
        {
            TestingIsGood();
            TestingIsBad();
            //if (cobPAChannelOne.SelectedIndex == 7 && CheckTestResultState() == true)
            //{
            //    CloseAllFixture();

            //    MessageBox.Show("测试完毕！当前产品：合格",
            //        "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
            //else if (cobPAChannelOne.SelectedIndex == 7 && CheckTestResultState() == false)
            //{
            //    CloseAllFixture();

            //    MessageBox.Show("测试完毕！当前产品：不合格",
            //        "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //}
        }
        private bool CheckTestResultState()
        {
            foreach (bool b in testResult)
            {
                if (b == false)
                {
                    return false;
                }
            }
            return true;
        }
        private bool CheckTestStep()
        {
            foreach (bool b in testStep)
            {
                if (b == false)
                {
                    return false;
                }
            }
            return true;
        }
        private void InitalizationTestStepState() 
        {
            for (int i = 0; i <= testStep.Length - 1; i++)
            {
                testStep[i] = false;
            }
        }
        private void SetTestStepState(int index)
        {
            testStep[index] = true;
        }
        private bool GetTestStepState(int index)
        {
            return testStep[index];
        }

        //////////////////////////////////////////////////////////////////////////
        //date:2012-12-07
        //author:xiejun
        //content:math of multiport-TestFixture.
        //////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// 多端口夹具校准中，夹具开关的参数容器包。
        /// </summary>
        Dictionary<byte, byte> _SwichRFArgument = new Dictionary<byte, byte>();
        private void SetSwichRFArgument(byte portName, byte portState)
        {
            _SwichRFArgument.Add(portName, portState);
        }
        private Dictionary<byte, byte> GetSwichRFArgument()
        {
            return _SwichRFArgument;
        }

        /// <summary>
        /// 多端口夹具校准中，频谱仪补偿值的容器包。
        /// </summary>
        IList<double> _MulitPortTestFixtureCalibarteValueBag = new List<double>();
        private void SetMulitPortTestFixtureCalibarteValue(double arg)
        {
            _MulitPortTestFixtureCalibarteValueBag.Add(arg);
        }
        public IList<double> GetMulitPortTestFixtureCalibarteValue()
        {
            return this._MulitPortTestFixtureCalibarteValueBag;
        }
        
        private void MultiPortTestFixture()
        {
            int _index = -1;

            foreach (string arg in _testStep)
            {
                _index++;                
                testingEnter.SetSwitchRF(Convert.ToInt16(_fixtureCommand[_index]));
                SinglePortTest();
            }
        }
        /// <summary>
        /// initialization test step.
        /// </summary>
        private void InitTestStep()
        {
            try
            {
                cobPAChannelOne.Items.Clear();

                for (int i = 0; i <= testingEnter.GetTestStep().Length - 1; i++)
                {
                    cobPAChannelOne.Items.Add(testingEnter.GetTestStep()[i]);
                }
                cobPAChannelOne.SelectedIndex = 0;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// choose test type
        /// </summary>
        /// <param name="testType">MulitPort-Testing,SinglePort-Testing</param>
        private void ChooseTestType(string testType)
        {
            try
            {
                switch (testType)
                {
                    case "MulitPort-Testing":
                        MultiPortTestFixture();
                        break;

                    case "SinglePort-Testing":
                        SinglePortTest();
                        break;
                }
            }
            catch (System.ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        /// <summary>
        /// choose initialization type
        /// </summary>
        /// <param name="testType">MulitPort-Testing,SinglePort-Testing</param>
        private void ChooseInitType(string testType)
        {
            try
            {
                switch (testType)
                {
                    case "MulitPort-Testing":
                        InitMultiPortTestFixture();
                        break;

                    case "SinglePort-Testing":
                        InitSinglePortTest();
                        break;
                }
            }
            catch (System.ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void InitMultiPortTestFixture()
        {
            //get test step
            _testStep = testingEnter.GetTestStep();
            //get product command
            _productCommand = testingEnter.GetProductCommand();
            //get test index
            _testIndex = testingEnter.GetTestIndex();
            //get mutliport testfixture command
            _fixtureCommand = testingEnter.GetFixtureCommand();
            //get test limit
            _testLimit = testingEnter.GetTestLimit();

            InitTestStep();
            datas = new string[cobPAChannelOne.Items.Count];
            testResult = new bool[cobPAChannelOne.Items.Count];
            InitCheckOutState();
            cobPAChannelOne.SelectedIndex = 0;
        }
        private void InitSinglePortTest()
        {
            datas = new string[cobPAChannelOne.Items.Count];
            testResult = new bool[cobPAChannelOne.Items.Count];
            testStep = new bool[cobPAChannelOne.Items.Count];
            InitCheckOutState();
            cobPAChannelOne.SelectedIndex = 0;
            //get test step
            _testStep = testingEnter.GetTestStep();
            //get product command
            _productCommand = testingEnter.GetProductCommand();
            //get test index
            _testIndex = testingEnter.GetTestIndex();
            //get mutliport testfixture command
            _fixtureCommand = testingEnter.GetFixtureCommand();
            //get test limit
            _testLimit = testingEnter.GetTestLimit();

        }
        /// <summary>
        /// 选择校准方式
        /// </summary>
        /// <param name="calibarteType">
        /// 1.CalibarteMultiPortTestFixture() 
        /// 2.CalibarteSinglePortTest()
        /// </param>
        private void ChooseCalibarteType(string calibarteType)
        {
            try
            {
                switch (calibarteType)
                {
                    case "MulitPort-Testing":
                        CalibarteMultiPortTestFixture();
                        break;

                    case "SinglePort-Testing":
                        CalibarteSinglePortTest_CableAddAttenuator();
                        //CalibarteSinglePortTest_IgnoreCable();
                        break;
                }
            }
            catch (System.ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 校准多端口夹具
        /// 其步骤分：2
        /// 1 - 设置频谱仪的补偿值归零
        /// 2 - 设置添加测试设备（多端口夹具、衰减器、等）后频谱仪的补偿值、并记录补偿值。
        /// </summary>
        private void CalibarteMultiPortTestFixture()
        {
            SetSpectrumAnalyzerOffsetZeor();
            SetSpectrumAnalyzerOffsetOfAppendedTestFixture();
            MessageBox.Show("仪表校准完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
        private void SetSpectrumAnalyzerOffsetZeor()
        {
            MessageBox.Show("请连接信号源、频谱仪。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            double power = 0;
            double offset = 0;
            testingEnter.iSG1.SetRFFrequency(2595000000);
            testingEnter.iSG1.SetModState(0);
            testingEnter.iSA.SetRefLvlOffset(0);
            testingEnter.iSA.SetCenterFrequency(2595000000);
            testingEnter.iSA.SetFrequencySpan(5000);
            testingEnter.iSG1.SetRFAmplitude(0);
            testingEnter.iSG1.SetRFOutputState(true);
            power = 0;
            Thread.Sleep(2000);
            testingEnter.iSA.SetMaxMark();
            Thread.Sleep(3000);
            testingEnter.iSA.GetMARKerPower(1, ref power);
            offset = (power * -1);
            testingEnter.iSA.SetRefLvlOffset(offset);
            testingEnter.iSA.Rlevel(0);
            testingEnter.iSA.Rlevel(50);
            testingEnter.iSG1.SetRFOutputState(false);
            testingEnter.iSG1.SetRFAmplitude(-30);
        }
        private void SetSpectrumAnalyzerOffsetOfAppendedTestFixture()
        {
            MessageBox.Show("请连接信号源、多端口夹具、衰减器。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            TestingEnter.SwichRF _swichRF = new TestingEnter.SwichRF();
            
            testingEnter.InitSwichRF(_swichRF);
            
            SetSwichRFArgument(_swichRF.ANT1, _swichRF.ON);
            SetSwichRFArgument(_swichRF.ANT2, _swichRF.ON);
            SetSwichRFArgument(_swichRF.ANT3, _swichRF.ON);
            SetSwichRFArgument(_swichRF.ANT4, _swichRF.ON);
            foreach (KeyValuePair<byte, byte> kvp in _SwichRFArgument)
            {
                testingEnter.SetSwitchRF(kvp.Key, kvp.Value);
                SetSpectrumAnalyzer();
            }
            SetDigitalPower(28.5, 5.7, 10, 10);
        }
        private void CalibarteSinglePortTest_IgnoreCable()
        {
            testingEnter.iSG1.SetRFFrequency(2595000000);
            testingEnter.iSG1.SetModState(0);
            testingEnter.iSA.SetRefLvlOffset(0);
            testingEnter.iSA.SetCenterFrequency(2595000000);
            testingEnter.iSA.SetFrequencySpan(5000);
            testingEnter.iSG1.SetRFAmplitude(0);
            MessageBox.Show("接衰减器，开始校准仪表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            
            testingEnter.iSG1.SetRFOutputState(true);
            double power = 0;
            Thread.Sleep(2000);
            testingEnter.iSA.SetMaxMark();
            Thread.Sleep(3000);
            testingEnter.iSA.GetMARKerPower(1, ref power);
            double offset = (power * -1);
            testingEnter.iSA.SetRefLvlOffset(offset);
            testingEnter.iSA.Rlevel(0);
            testingEnter.iSG1.SetRFOutputState(false);
            testingEnter.iSG1.SetRFAmplitude(-30);
            testingEnter.iSA.Rlevel(50);
            SetDigitalPower(28.5, 5.7, 10, 10);
            MessageBox.Show("仪表校准完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        private void CalibarteSinglePortTest_CableAddAttenuator()
        {
            if (CalibarteSinglePortTest_Cable() == true && CalibarteSinglePortTest_Attenuator() == true)
            {
                WriteOffsetCableAddAttenuator();

                MessageBox.Show("仪表校准完毕！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                return;
            }
        }
        private void SetSpectrumAnalyzer()
        {
            double power = 0;
            double offset = 0;

            testingEnter.iSG1.SetRFAmplitude(0);
            testingEnter.iSG1.SetRFOutputState(true);
            power = 0;
            Thread.Sleep(2000);
            testingEnter.iSA.SetMaxMark();
            Thread.Sleep(3000);
            testingEnter.iSA.GetMARKerPower(1, ref power);
            offset = (power * -1);
            testingEnter.iSA.SetRefLvlOffset(offset);
            testingEnter.iSA.Rlevel(0);
            testingEnter.iSA.Rlevel(50);
            testingEnter.iSG1.SetRFOutputState(false);
            testingEnter.iSG1.SetRFAmplitude(-30);
            SetMulitPortTestFixtureCalibarteValue(offset);
        }
        private void SetDigitalPower(double iPM1VOLT, double iPM2VOLT, double iPM1Current, double iPM2Current)
        {
            testingEnter.iPM1.SetVOLT(iPM1VOLT);
            testingEnter.iPM2.SetVOLT(iPM2VOLT);
            testingEnter.iPM1.SetCurrent(iPM1Current);
            testingEnter.iPM2.SetCurrent(iPM2Current);
        }
        private bool CalibarteSinglePortTest_Cable()
        {
            try
            {
                MessageBox.Show("请连接信号源、频谱仪！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                double powerCable = 0;
                double offsetCable = 0;

                testingEnter.iSA.Reset();
                testingEnter.iSG1.SetRFFrequency(2595000000);
                testingEnter.iSG1.SetModState(0);
                testingEnter.iSA.SetCenterFrequency(2595000000);
                testingEnter.iSA.SetFrequencySpan(5000);
                testingEnter.iSG1.SetRFAmplitude(0);
                testingEnter.iSG1.SetRFOutputState(true);
                Thread.Sleep(2000);
                testingEnter.iSA.SetMaxMark();
                Thread.Sleep(3000);
                testingEnter.iSA.GetMARKerPower(1, ref powerCable);
                offsetCable = (powerCable * -1);
                testingEnter.iSA.SetRefLvlOffset(offsetCable);
                testingEnter.iSA.Rlevel(0);
                testingEnter.iSG1.SetRFOutputState(false);

                return true;
            }
            catch (NullReferenceException e)
            {
                MessageBox.Show("连接信号源、频谱仪校准失败！详细：" + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
            catch (Exception e)
            {
                MessageBox.Show("连接信号源、频谱仪校准失败！详细：" + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }

        }
        private bool CalibarteSinglePortTest_Attenuator()
        {
            try 
            {
                MessageBox.Show("接衰减器，开始校准仪表！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

                double powerCableAddAttenuator = 0;
                double offsetCableAddAttenuator = 0;

                testingEnter.iSG1.SetRFOutputState(true);
                Thread.Sleep(2000);
                testingEnter.iSA.SetMaxMark();
                Thread.Sleep(3000);
                testingEnter.iSA.GetMARKerPower(1, ref powerCableAddAttenuator);
                offsetCableAddAttenuator = (powerCableAddAttenuator * -1);
                testingEnter.iSA.SetRefLvlOffset(offsetCableAddAttenuator);
                SetOffsetCableAddAttenuator(offsetCableAddAttenuator);
                testingEnter.iSA.Rlevel(0);
                testingEnter.iSG1.SetRFOutputState(false);
                testingEnter.iSG1.SetRFAmplitude(-30);
                testingEnter.iSA.Rlevel(50);
                SetDigitalPower(28.5, 5.7, 10, 3);
                return true;
            }
            catch (NullReferenceException e)
            {
                MessageBox.Show("连接信号源、频谱仪校准失败！详细：" + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }
            catch (Exception e)
            {
                MessageBox.Show("连接信号源、频谱仪校准失败！详细：" + e.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return false;
            }

        }
        private double _offsetCableAddAttenuator = 0;
        public void SetOffsetCableAddAttenuator(double arg)
        {
            try
            {
                this._offsetCableAddAttenuator = arg;
            }
            catch(ArgumentNullException e)
            {
                MessageBox.Show(e.Message);
            }
        }
        public double GetOffsetCableAddAttenuator()
        {
            return this._offsetCableAddAttenuator;
        }
        private bool WriteOffsetCableAddAttenuator()
        {
            try 
            {
                string pathFile = Directory.GetCurrentDirectory() + @"/CalibrateFile.txt";

                if (!File.Exists(pathFile))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(pathFile))
                    {
                        sw.WriteLine(GetOffsetCableAddAttenuator().ToString());
                    }
                }
                else
                {
                    File.Delete(pathFile);
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(pathFile))
                    {
                        sw.WriteLine(GetOffsetCableAddAttenuator().ToString());
                    }
                }

                return true;
            }
            catch(IOException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            catch (ArgumentNullException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }

        }
        private bool ReadOffsetCableAddAttenuator()
        {
            try
            {
                string pathFile = Directory.GetCurrentDirectory() + @"/CalibrateFile.txt";

                // Open the file to read from.
                using (StreamReader sr = File.OpenText(pathFile))
                {
                    string s = "";

                    while ((s = sr.ReadLine().Trim()) != null)
                    {
                        testingEnter.iSA.SetRefLvlOffset(Convert.ToDouble(s));

                        if (sr.EndOfStream == true)
                        {
                            return true;
                        }
                    }
                }

                return true;
            }
            catch (IOException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }
            catch (ArgumentNullException e)
            {
                MessageBox.Show(e.Message);
                return false;
            }

        }
    }
}
